//更新售后服务单
import React, { useState, useEffect } from 'react';
import useStore from '../../components/useStore';
import { 
  Button, Card, Form, notification, Input, Select, Upload, 
  DatePicker, InputNumber, Modal, Spin, Collapse, Divider, Row, Col 
} from 'antd';
import { DownloadOutlined, UploadOutlined, InfoCircleOutlined } from '@ant-design/icons';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import store from '../../untils/store';
import dayjs from 'dayjs';
import request from '../../untils/request';

const { Panel } = Collapse;

const UpdateAfterSales = () => { 
  const { collapsed } = useStore();
  const { localUrl } = store();
  const [afterSalesDetail, setafterSalesDetail] = useState({});
  const [afterSalesForm] = Form.useForm();
  const [afterSalesUsers, setafterSalesUsers] = useState([]); 
  const [main_problem_content_html, setmain_problem_content_html] = useState(BraftEditor.createEditorState(null));
  const [specific_solution_measures_html, setspecific_solution_measures_html] = useState(BraftEditor.createEditorState(null));
  const [problemDescriptionListFile, setProblemDescriptionListFile] = useState(null);
  const [problemSolvingSolutionFile, setProblemSolvingSolutionFile] = useState(null);
  const [uploading, setUploading] = useState(false);

  // 文件上传前置处理
  const handleBeforeUpload = (fileType) => (file) => {
    switch (fileType) {
      case "problem_description_list":
        setProblemDescriptionListFile(file);
        break;
      case "problem_solving_solution":
        setProblemSolvingSolutionFile(file);
        break;
    }
    return false;
  };

  const save = async () => {
    try {
      const values = await afterSalesForm.validateFields();
      const formData = new FormData();
      setUploading(true);

      // 固定字段
      formData.append('id', afterSalesDetail.id);
      formData.append('service_order_id', values.service_order_id);
      formData.append('sn', values.sn);
      formData.append('is_mw', values.is_mw);
      
      // 富文本内容
      formData.append('main_problem_content_html', BraftEditor.createEditorState(main_problem_content_html).toHTML());
      formData.append('specific_solution_measures_html', BraftEditor.createEditorState(specific_solution_measures_html).toHTML());

      // 日期字段处理
      if (values.service_time) {
        formData.append('service_time', dayjs(values.service_time).format('YYYY-MM-DD HH:mm:ss'));
      }

      // 基础字段处理
      const basicFields = [
        'contract_number', 'sales_order_id', 'after_sales_person_id',
        'money', 'time', 'need_bom_number'
      ];
      basicFields.forEach(field => {
        if (values[field] !== null && values[field] !== undefined) {
          formData.append(field, values[field]);
        }
      });

      // 文件字段处理
      const fileFields = [
        { state: problemDescriptionListFile, detail: afterSalesDetail.problem_description_list, name: 'problem_description_list' },
        { state: problemSolvingSolutionFile, detail: afterSalesDetail.problem_solving_solution, name: 'problem_solving_solution' }
      ];

      fileFields.forEach(({ state, detail, name }) => {
        if (state) {
          formData.append(name, state);
        } else if (detail) {
          formData.append(name, detail);
        }
      });

      // 发送请求
      fetch("/admin/afterSales/updateOrder", {
        method: "POST",
        body: formData,
        headers:{
          Authorization: `Bearer ${JSON.parse(localStorage.getItem('user')).token}`
        }
      }).then(response => response.json())
        .then(data => {
          if (data.code === 200) {
            notification.success({ message: data.msg });
          } else {
            notification.error({ message: data.msg || "上传失败" });
          }
          setTimeout(() => setUploading(false), 300);
        });
    } catch (errorInfo) {
      notification.error({ message: "请检查填写信息是否有误" });
    }
  };

  useEffect(() => { 
    // 获取ID参数
    const hash = window.location.hash.slice(1); 
    const queryString = hash.split('?')[1]; 
    let id = null;
    
    if (queryString) {
      const queryParams = new URLSearchParams(queryString);
      id = parseInt(queryParams.get('id')); 
    } else {
      notification.error("没有找到 id 参数");
    }

    // 获取售后人员列表
    request("/admin/user/getAfterSalesUsers", {
      mode: 'cors'
    }).then(data => setafterSalesUsers(data));

    // 获取售后服务单详情
    request("/admin/afterSales/getAfterSalesInfo", { 
      method: "POST",
      mode: 'cors',
      body: { id }
    }).then(data => {
        if (data.code === 200) {
          const formattedData = {
            ...data.data,
            service_time: data.data.service_time ? dayjs(data.data.service_time) : null,
          };
          setmain_problem_content_html(BraftEditor.createEditorState(data.data.main_problem_content_html));
          setspecific_solution_measures_html(BraftEditor.createEditorState(data.data.specific_solution_measures_html));
          setafterSalesDetail(formattedData);
          afterSalesForm.setFieldsValue(formattedData);
          notification.success({ message: data.msg });
        } else {
          notification.open({ message: "未知错误" });
        }
      });
  }, []);

  return (
    <div style={{ 
      height: "94%", 
      backgroundColor: `#F1F1F1`, 
      right: "1%", 
      top: "4vh", 
      overflow: "hidden",
      backgroundSize: "100% 100%", 
      width: collapsed ? "94%" : "84%", 
      position: "absolute", 
      color: "white", 
      fontSize: "0.8rem" 
    }}>
      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem", 
          position: "relative", 
          width: "96%", 
          marginLeft: "2%", 
          backgroundColor: "", 
          display: "flex",
          textIndent: "1rem", 
          justifyContent: "flex-start", 
          alignContent: "flex-start", 
          flexWrap: "wrap"
        }}>
          <Card style={{ width: "100%", marginTop: "2vh" }}>
            <div style={{ maxHeight: "75vh", overflowY: "scroll" }}>
              <Form style={{ width: "95%" }} form={afterSalesForm}> 
                {/* 不可更改区域 */}
                <h3 style={{ 
                  color: '#1890ff', 
                  margin: '0 0 12px', 
                  fontSize: 16, 
                  display: 'flex', 
                  alignItems: 'center' 
                }}>
                  <InfoCircleOutlined style={{ marginRight: 6 }} /> 以下信息不可更改
                </h3>
                <Divider style={{ margin: '0 0 16px' }} />
                
                <Row gutter={[16, 16]}>
                  {/* 第一列 - 服务单号 */}
                  <Col xs={24} sm={8} md={8} lg={8}>
                    <Form.Item
                      name="service_order_id"
                      label="服务单号（不可改动）"
                      labelCol={{ span: 24 }}
                      wrapperCol={{ span: 24 }}
                    >
                      <Input placeholder='服务单号为空' disabled />
                    </Form.Item>
                  </Col>
                  
                  {/* 第二列 - 对应产品SN */}
                  <Col xs={24} sm={8} md={8} lg={8}>
                    <Form.Item
                      name="sn"
                      label="对应产品SN（不可改动）"
                      labelCol={{ span: 24 }}
                      wrapperCol={{ span: 24 }}
                    >
                      <Input placeholder='对应产品SN为空' disabled />
                    </Form.Item>
                  </Col>
                  
                  {/* 第三列 - 对应销售订单号 */}
                  <Col xs={24} sm={8} md={8} lg={8}>
                    <Form.Item
                      name="sales_order_id"
                      label="对应销售订单号（不可改动）"
                      labelCol={{ span: 24 }}
                      wrapperCol={{ span: 24 }}
                    >
                      <Input disabled placeholder='对应销售订单号为空' />
                    </Form.Item>
                  </Col>
                </Row>
                
                {/* 富文本编辑区域标题 */}
                <h3 style={{ 
                  color: '#1890ff', 
                  margin: '24px 0 12px', 
                  fontSize: 16, 
                  display: 'flex', 
                  alignItems: 'center' 
                }}>
                  <InfoCircleOutlined style={{ marginRight: 6 }} /> 问题与解决方案
                </h3>
                <Divider style={{ margin: '0 0 16px' }} />
                
                <Collapse style={{ width: '100%' }}>
                  <Panel header="问题解决方案" key="2">
                    <Form.Item label="主要问题内容">
                      <BraftEditor
                        value={main_problem_content_html}
                        onChange={setmain_problem_content_html}
                        style={{ height: "20vh !important", border: "1px solid gray" }}
                        media={{ uploadFn: () => { } }}  
                        excludeControls={["media"]}     
                      />
                    </Form.Item>
                    
                    <Form.Item label="具体解决方案措施">
                      <BraftEditor
                        style={{ height: "20vh !important", border: "1px solid gray" }}
                        value={specific_solution_measures_html}
                        onChange={setspecific_solution_measures_html}
                        placeholder="具体解决方案措施为空"
                        media={{ uploadFn: () => { } }}  
                        excludeControls={["media"]}     
                      />
                    </Form.Item>
                  </Panel>
                </Collapse>
                
                {/* 基础信息 */}
                <h3 style={{ 
                  color: '#1890ff', 
                  margin: '24px 0 12px', 
                  fontSize: 16, 
                  display: 'flex', 
                  alignItems: 'center' 
                }}>
                  <InfoCircleOutlined style={{ marginRight: 6 }} /> 基础信息
                </h3>
                <Divider style={{ margin: '0 0 16px' }} />
                
                {/* 表单项布局 */}
                <Row gutter={[16, 24]}>
                  {/* 第一行两列 */}
                  <Col xs={24} sm={12} md={12} lg={12}>
                    <Form.Item
                      label="是否维保内"
                      name="is_mw"
                    >
                      <Select
                        options={[
                          { value: 0, label: "否" },
                          { value: 1, label: "是" }
                        ]}
                        placeholder="是否维保内为空"
                      />
                    </Form.Item>
                  </Col>
                  
                  <Col xs={24} sm={12} md={12} lg={12}>
                    <Form.Item
                      label="服务时间"
                      name="service_time"
                    >
                      <DatePicker showTime placeholder='服务时间为空' />
                    </Form.Item>
                  </Col>

                  {/* 第二行两列 */}
                  <Col xs={24} sm={12} md={12} lg={12}>
                    <Form.Item
                      label="对应合同号"
                      name="contract_number"
                    >
                      <Input maxLength={50} showCount placeholder='对应合同号为空' />
                    </Form.Item>
                  </Col>
                  
                  <Col xs={24} sm={12} md={12} lg={12}>
                    <Form.Item
                      label="售后人员"
                      name="after_sales_person_id"
                      extra="显示数字时表示原售后人员已经不属于售后"
                    >
                      <Select options={afterSalesUsers} placeholder="售后人员为空" />
                    </Form.Item>
                  </Col>

                  {/* 第三行两列 */}
                  <Col xs={24} sm={12} md={12} lg={12}>
                    <Form.Item
                      label="服务费用"
                      name="money"
                      rules={[{
                        validator: (_, value) => {
                          if (!value && value !== 0) return Promise.resolve();
                          const strValue = value.toString();
                          if (strValue.replace(/[.]/, '').length > 15) {
                            return Promise.reject(new Error('服务费用总长度不能超过15位'));
                          }
                          return Promise.resolve();
                        }
                      }]}
                    >
                      <InputNumber
                        precision={2} 
                        step={0.01}
                        formatter={value => value?.toString()} 
                        parser={value => value.replace(/[^\d.]/g, '')} 
                        style={{ width: '100%' }}
                        placeholder='最长为15位数（含小数点与小数）'
                        prefix="¥" 
                      />
                    </Form.Item>
                  </Col>
                  
                  <Col xs={24} sm={12} md={12} lg={12}>
                    <Form.Item
                      label="工时"
                      name="time"
                      rules={[{
                        validator: (_, value) => {
                          if (!value && value !== 0) return Promise.resolve();
                          const strValue = value.toString();
                          if (strValue.replace(/[.]/, '').length > 5) {
                            return Promise.reject(new Error('总长度不能超过5位'));
                          }
                          return Promise.resolve();
                        }
                      }]}
                    >
                      <InputNumber
                        precision={1} 
                        step={0.1}
                        formatter={value => value?.toString()} 
                        parser={value => value.replace(/[^\d.]/g, '')} 
                        style={{ width: '100%' }}
                        placeholder='最长为5位数（含小数点与小数）'
                        suffix="小时"
                      />
                    </Form.Item>
                  </Col>

                  {/* 单独一行 */}
                  <Col xs={24}>
                    <Form.Item
                      label="需要替换物料"
                      name="need_bom_number"
                    >
                      <Input maxLength={50} showCount placeholder='需要替换物料为空' />
                    </Form.Item>
                  </Col>
                </Row>
                
                {/* 附件 */}
                <h3 style={{ 
                  color: '#1890ff', 
                  margin: '24px 0 12px', 
                  fontSize: 16, 
                  display: 'flex', 
                  alignItems: 'center' 
                }}>
                  <InfoCircleOutlined style={{ marginRight: 6 }} /> 附件（新上传的文件将覆盖旧文件，但不会影响到其他表单引用旧文件）
                </h3>
                <Divider style={{ margin: '0 0 16px' }} />
                
                <Form.Item
                  label="问题描述清单"
                  name="problem_description_list"
                >
                  {/* 问题描述清单下载按钮 */}
                  {afterSalesDetail.problem_description_list ? (
                    <a 
                      href={`${localUrl}${afterSalesDetail.problem_description_list}`} 
                      target="_blank" 
                      rel="noopener noreferrer"
                    >
                      <Button icon={<DownloadOutlined />}>下载问题描述清单</Button>
                    </a>
                  ) : (
                    <div>没有上传问题描述清单</div>
                  )}
                  
                  <Upload
                    maxCount={1}
                    beforeUpload={handleBeforeUpload('problem_description_list')}
                    onRemove={() => {
                      setProblemDescriptionListFile(null);
                      return true;
                    }}
                    fileList={problemDescriptionListFile ? [{
                      uid: problemDescriptionListFile.uid || Date.now().toString(),
                      name: problemDescriptionListFile.name,
                      status: 'done'
                    }] : []}
                  >
                    <Button style={{ marginTop: "2vh" }} icon={<UploadOutlined />}>重新上传文件</Button>
                  </Upload>
                </Form.Item>
                
                <Form.Item
                  label="问题解决方案"
                  name="problem_solving_solution"
                >
                  {/* 问题解决方案下载按钮 */}
                  {afterSalesDetail.problem_solving_solution ? (
                    <a 
                      href={`${localUrl}${afterSalesDetail.problem_solving_solution}`} 
                      target="_blank" 
                      rel="noopener noreferrer"
                    >
                      <Button icon={<DownloadOutlined />}>下载问题解决方案</Button>
                    </a>
                  ) : (
                    <div>没有上传问题解决方案</div>
                  )}
                  
                  <Upload
                    maxCount={1}
                    beforeUpload={handleBeforeUpload('problem_solving_solution')}
                    onRemove={() => {
                      setProblemSolvingSolutionFile(null);
                      return true;
                    }}
                    fileList={problemSolvingSolutionFile ? [{
                      uid: problemSolvingSolutionFile.uid || Date.now().toString(),
                      name: problemSolvingSolutionFile.name,
                      status: 'done'
                    }] : []}
                  >
                    <Button style={{ marginTop: "2vh" }} icon={<UploadOutlined />}>重新上传文件</Button>
                  </Upload>
                </Form.Item>
                
                <Button type='primary' onClick={save} style={{ marginTop: '2vh' }}>保存更改</Button>
              </Form>
            </div>
          </Card>
          
          {/* 上传加载模态框 - 保持原有属性 */}
          <Modal
            open={uploading}
            centered
            closable={false}
            footer={null}
            maskClosable={false}
            width={400}
            bodyStyle={{ textAlign: 'center', padding: '30px 20px' }}
          >
            <Spin />
            <div style={{ marginTop: 20, fontSize: 16, fontWeight: 'bold', color: '#333' }}>
              上传中
            </div>
            <div style={{ marginTop: 10, color: '#666' }}>
              请勿关闭页面或进行其他操作
            </div>
          </Modal>
        </div>
      </div>
    </div>
  );
};

export default UpdateAfterSales;

// 仅保留正在使用的样式定义，确保页面布局不变
const styles = {
  kshcontainer: {
    width: "98%", 
    height: "95%", 
    position: "absolute", 
    top: "3%", 
    left: "1%", 
    backgroundColor: "white", 
    color: "black",
    borderRadius: "10px",
  },
};
